package com.yiranLTD.service.userService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiranLDT.Result;
import com.yiranLDT.User;
import com.yiranLTD.controller.UserController;
import com.yiranLTD.mapper.UserMapper;
import com.yiranLTD.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<User> login(String username, String password) {
        //根据Username（username有唯一约束）拿到需要登录的用户
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        List<User> users = userMapper.selectList(userLambdaQueryWrapper);
        if(users==null || users.isEmpty()){
            log.info("用户名错误！");
            throw new RuntimeException("用户名输入错误");
        }
        User user = users.get(0);
        String password1 = user.getPassword();
        String salt = user.getSalt();
        password=password+salt;
        MessageDigest instance = null;
        try {
            instance = MessageDigest.getInstance(UserController.HASH_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] digest = instance.digest(password.getBytes(StandardCharsets.UTF_8));
        String passwordAndSalt= Base64.getEncoder().encodeToString(digest);
        if(!password1.equals(passwordAndSalt)){
            log.info("密码错误！");
            log.info(passwordAndSalt);
            log.info(password1);
            throw new RuntimeException("密码错误！");
        }
        user.setSalt(null);
        user.setPassword(null);
        return Result.success(user);
    }
}
